package com.djf.djfcs.controller;

import com.djf.djfcs.entity.es.ProductDocument;
import com.djf.djfcs.esService.ProductEsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品Elasticsearch控制器
 * 提供商品ES文档的增删改查API
 */
@Slf4j
@RestController
@RequestMapping("/api/es/products")
public class ProductEsController {

    @Autowired
    private ProductEsService productEsService;

    /**
     * 创建商品索引
     */
    @PostMapping("/index")
    public ResponseEntity<Map<String, Object>> createProductIndex() {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean created = productEsService.createProductIndex();
            if (created) {
                result.put("success", true);
                result.put("message", "商品索引创建成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "商品索引已存在");
                return ResponseEntity.ok(result);
            }
        } catch (IOException e) {
            log.error("创建商品索引失败", e);
            result.put("success", false);
            result.put("message", "创建商品索引失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 索引商品文档（新增或更新）
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> indexProduct(@RequestBody ProductDocument productDocument) {
        Map<String, Object> result = new HashMap<>();
        try {
            String documentId = productEsService.indexProduct(productDocument);
            result.put("success", true);
            result.put("message", "商品文档索引成功");
            result.put("documentId", documentId);
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            log.error("索引商品文档失败", e);
            result.put("success", false);
            result.put("message", "索引商品文档失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 根据ID获取商品文档
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getProductById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            ProductDocument productDocument = productEsService.getProductById(id);
            if (productDocument != null) {
                result.put("success", true);
                result.put("message", "获取商品文档成功");
                result.put("data", productDocument);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "商品文档不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
        } catch (IOException e) {
            log.error("获取商品文档失败", e);
            result.put("success", false);
            result.put("message", "获取商品文档失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 根据商品编码获取商品文档
     */
    @GetMapping("/code/{productCode}")
    public ResponseEntity<Map<String, Object>> getProductByCode(@PathVariable String productCode) {
        Map<String, Object> result = new HashMap<>();
        try {
            ProductDocument productDocument = productEsService.getProductByCode(productCode);
            if (productDocument != null) {
                result.put("success", true);
                result.put("message", "获取商品文档成功");
                result.put("data", productDocument);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "商品文档不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
        } catch (IOException e) {
            log.error("获取商品文档失败", e);
            result.put("success", false);
            result.put("message", "获取商品文档失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 搜索商品文档
     */
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchProducts(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String brand,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) BigDecimal minPrice,
            @RequestParam(required = false) BigDecimal maxPrice,
            @RequestParam(required = false) Integer minStock,
            @RequestParam(required = false) Integer maxStock,
            @RequestParam(defaultValue = "0") int from,
            @RequestParam(defaultValue = "10") int size) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            List<ProductDocument> productDocuments = productEsService.searchProducts(
                    keyword, category, brand, status, minPrice, maxPrice, 
                    minStock, maxStock, from, size);
            
            result.put("success", true);
            result.put("message", "搜索商品文档成功");
            result.put("data", productDocuments);
            result.put("total", productDocuments.size());
            result.put("from", from);
            result.put("size", size);
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            log.error("搜索商品文档失败", e);
            result.put("success", false);
            result.put("message", "搜索商品文档失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 更新商品文档
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateProduct(
            @PathVariable Long id, 
            @RequestBody Map<String, Object> updates) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            String documentId = productEsService.updateProduct(id, updates);
            result.put("success", true);
            result.put("message", "商品文档更新成功");
            result.put("documentId", documentId);
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            log.error("更新商品文档失败", e);
            result.put("success", false);
            result.put("message", "更新商品文档失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 更新商品库存
     */
    @PutMapping("/{id}/stock")
    public ResponseEntity<Map<String, Object>> updateProductStock(
            @PathVariable Long id, 
            @RequestParam Integer stock) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            String documentId = productEsService.updateProductStock(id, stock);
            result.put("success", true);
            result.put("message", "商品库存更新成功");
            result.put("documentId", documentId);
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            log.error("更新商品库存失败", e);
            result.put("success", false);
            result.put("message", "更新商品库存失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 更新商品价格
     */
    @PutMapping("/{id}/price")
    public ResponseEntity<Map<String, Object>> updateProductPrice(
            @PathVariable Long id, 
            @RequestParam BigDecimal price) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            String documentId = productEsService.updateProductPrice(id, price);
            result.put("success", true);
            result.put("message", "商品价格更新成功");
            result.put("documentId", documentId);
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            log.error("更新商品价格失败", e);
            result.put("success", false);
            result.put("message", "更新商品价格失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 更新商品状态
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<Map<String, Object>> updateProductStatus(
            @PathVariable Long id, 
            @RequestParam String status) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            String documentId = productEsService.updateProductStatus(id, status);
            result.put("success", true);
            result.put("message", "商品状态更新成功");
            result.put("documentId", documentId);
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            log.error("更新商品状态失败", e);
            result.put("success", false);
            result.put("message", "更新商品状态失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 删除商品文档
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteProduct(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean deleted = productEsService.deleteProduct(id);
            if (deleted) {
                result.put("success", true);
                result.put("message", "商品文档删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "商品文档不存在或删除失败");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
        } catch (IOException e) {
            log.error("删除商品文档失败", e);
            result.put("success", false);
            result.put("message", "删除商品文档失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 批量索引商品文档
     */
    @PostMapping("/batch")
    public ResponseEntity<Map<String, Object>> batchIndexProducts(@RequestBody List<ProductDocument> productDocuments) {
        Map<String, Object> result = new HashMap<>();
        try {
            int successCount = productEsService.batchIndexProducts(productDocuments);
            result.put("success", true);
            result.put("message", "批量索引商品文档完成");
            result.put("successCount", successCount);
            result.put("totalCount", productDocuments.size());
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            log.error("批量索引商品文档失败", e);
            result.put("success", false);
            result.put("message", "批量索引商品文档失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 删除商品索引
     */
    @DeleteMapping("/index")
    public ResponseEntity<Map<String, Object>> deleteProductIndex() {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean deleted = productEsService.deleteProductIndex();
            if (deleted) {
                result.put("success", true);
                result.put("message", "商品索引删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "商品索引删除失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
            }
        } catch (IOException e) {
            log.error("删除商品索引失败", e);
            result.put("success", false);
            result.put("message", "删除商品索引失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
}